package com.ruoyi.merchant.controller;

import com.ruoyi.common.core.cg.pojo.Community;
import com.ruoyi.common.core.cg.pojo.Leader;
import com.ruoyi.common.core.cg.pojo.Store;
import com.ruoyi.merchant.dto.SaveRequest;
import com.ruoyi.merchant.service.UsersService;
import com.ruoyi.merchant.utils.Result;
import com.ruoyi.merchant.utils.ali.HttpUtils;
import io.jsonwebtoken.lang.Assert;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UsersService usersService;
    /**
     * 手机验证码
     *
     * @param request
     * @return
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/leader")
    public Result loginUser(String phone) {
        return usersService.loginUser(phone);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest request) {
        System.err.println("手机号：" + request.getPhone() + " 密码：" + request.getPassword());
        return usersService.login(request.getPhone(), request.getPassword());
    }

    public static class LoginRequest {
        private String phone;
        private String password;

        // getters and setters
        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }


    }

    /**
     * 根据id查询四表关联
     * @param uid
     * @return
     */
    @GetMapping("/byId")
    public Result getUserById(Integer uid){
        Result result = usersService.selectById(uid);
        return result;
    }

    @RequestMapping("/save")
    public Result RequestSave(@RequestBody SaveRequest request){
        try {
            Community community = request.getCommunityData();
            Leader leader = request.getLeaderData();
            Store store = request.getStoreData();
            usersService.saveData(community,leader,store);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("请求失败");
        }
    }
    //发送短信
    @RequestMapping("code")
    public Result code(String phone) {
        System.err.println(phone);
        //生成随机验证码
        Random random = new Random();
        int i = random.nextInt(89999) + 10000;

        //保存验证码
        stringRedisTemplate.opsForValue().set(phone, i + "");

        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "d40b8d81e7df4d4f8294a08a4e50b15e";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        // 手机号码
        querys.put("mobile", phone);
        // 随机数 作为验证码
        querys.put("param", "**code**:"+i+",**minute**:5");

        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            System.err.println(1);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok("发送成功");
    }


    //验证码验证
    @RequestMapping("check")
    public Result check(String phone, String code) {
        Assert.notNull(phone, "手机号不能为空");

        Result loginUser = usersService.loginUser(phone);
        Integer status = loginUser.getStatus();
        System.out.println(loginUser+"jkadsjkajkda");
        System.err.println("返回值："+ status);
        System.out.println("获取到的id："+loginUser.getData());
        Assert.notNull(code, "验证码不能为空");

        System.err.println("手机号"+phone+"验证码："+code);
        // 从 Redis 获取验证码
        String c = stringRedisTemplate.opsForValue().get(phone);

        if (c == null || c.length() == 0) {
            return Result.error("验证码无效，请重新生成验证码");
        }

        if (!c.equals(code)) {
            return Result.error("你输入的验证码有误，请重新输入");
        }
        if(status == 200){
            return Result.build(200,"登录成功",loginUser);
        }else if(status == 100){
            return Result.build(100,"创建成功",loginUser);
        }
        return Result.error("登录失败");
    }
}

